import React, { useState, useEffect } from "react";
import styles from "../style/successful.module.css";
import { useNavigate } from "react-router-dom";
import searchIcon from "../img/dui.png";
import { home } from "../api/home";
// 定义商品数据接口
interface Product {
  id: number;
  title?: string;
  synopsis?: string;
  price: number | string;
  original_price?: number | string;
  img?: string;
}

function SuccessfulPage() {
  const [shopList, setShopList] = useState<Product[]>([]);
  const navigate = useNavigate();
  const user = JSON.parse(localStorage.getItem("user") || "null"); //用户数据
  console.log(user.data.token, "请求头token");
  console.log(user.data.id, "请求id");
  interface ApiResponse {
      data?: {
        list?: Product[];
      };
  }
  useEffect(() => {
    fetchShopList();
  }, []);


    const fetchShopList = async () => {
      try {
        // 检查 user.data 是否存在
        if (!user?.data?.token || !user?.data?.id) {
          console.error("用户数据不存在或 token/id 为空");
          return;
        }

        // 发送请求
        const res = await home({
          headers: {
            token: user.data.token,
            id: user.data.id,
          },
        });
        console.log("请求结果:", res);

        // 检查返回数据
        if (res.data && Array.isArray(res.data.data.list)) {
          setShopList(res.data.data.list);
        } else {
          console.error("返回数据格式不符合预期:", res.data);
          setShopList([]);
        }
      } catch (error) {
        console.error("获取推荐商品失败:", error);
      }
    };

  // 跳转到商品详情
  const handleItemClick = (id: string | number) => {
    localStorage.setItem("productId", id.toString());
    // 跳转到详情页面
    navigate("/detail");
  };

  const handleHome = () => {
    navigate("/home");
  };

  const handleOrder = () => {
    navigate("/orders");
  };

  return (
    <div style={{ backgroundColor: "#FAFAFA" }}>
      <div className={styles.top}>
        <b>购买成功</b>
      </div>

      <div className={styles.img}>
        <div className={styles.imgs}>
          <img src={searchIcon} alt="success" />
        </div>
        <p>购买成功</p>
        <div className={styles.two}>
          <div className={styles.shouye} onClick={handleHome}>
            返回首页
          </div>
          <div className={styles.dingdan} onClick={handleOrder}>
            查看订单
          </div>
        </div>
      </div>

      <div className={styles.three}>
        <div></div>
        <p>为您推荐</p>
        <div></div>
      </div>

      {/* 商品列表 */}
      <div className={styles.shop}>
        {shopList.map((product) => (
          <div
            key={product.id}
            className={styles.shop_item}
            onClick={() => handleItemClick(product.id)}
          >
            <img
              src={product.img || "./img/head.jpg"}
              alt={product.title || "商品"}
            />
            <p>{product.title || "商品名称"}</p>
            <span>{product.synopsis || "商品描述"}</span>
            <div className={styles.items}>
              <p>￥{Number(product.price).toFixed(2)}</p>
              {typeof product.original_price === "number" && (
                <del>￥{product.original_price.toFixed(2)}</del>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default SuccessfulPage;
